package com.myapp.handler;

import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.log4j.Logger;

import com.myapp.data.global.Instances;
import com.myapp.msg.base.BaseMsg;
import com.myapp.msg.define.MsgConfigBean;

/**
 * 解码器
 * 
 * @author jay 2011-4-20
 */
public class Decoder {
	// 日志
	private static Logger logger = Logger.getLogger(Decoder.class);

	public static BaseMsg decode(DataInputStream dis) {
		try {
			// 获取消息长度-读取message id
			int length = dis.readInt();
			if (length > Integer.MAX_VALUE) {
				throw new IOException(String.format(
						"Msg is too long[length:%d]!", length));
			}

			if (length <= 0) {
				throw new IOException(String.format(
						"Msg is too short[length:%d]!", length));
			}
			// 读取message id
			short id = dis.readShort();

			// 读取数据
			byte[] data = new byte[length - 2];
			dis.read(data);

			// 将数据植入buffer
			ByteBuffer buffer = ByteBuffer.allocate(length);
			buffer.put(data);
			buffer.flip();

			// 获取消息
			MsgConfigBean msgConfigBean = Instances.getMsgContainer()
					.getMsgConfigBean(id);

			// 判断此消息是否可用
			if (!msgConfigBean.isCanUse()) {
				return null;
			}

			// 初始化消息
			BaseMsg msg = null;
			if (msgConfigBean != null && msgConfigBean.getMsgClass() != null) {
				msg = msgConfigBean.getMsgClass().newInstance();
				msg.readBase(buffer);
			}

			// 设置消息配置
			msg.setMsgConfigBean(msgConfigBean);
			return msg;
		} catch (Exception e) {
			logger.error("Decode Message Error!", e);
		}
		return null;
	}
}
